﻿public class Solution {
    public int[][] GenerateMatrix(int n)
    {
        // 分配空间
        int[][] result = new int[n][];
        for (int i = 0; i < n; i++)
        {
            result[i] = new int[n];
        }
        
        // 赋值
        int loop = n / 2; // 循环圈数，从0开始记
        int num = 1; // 计数
        for (int l = 0; l < loop; l++)
        {
            // 从左到右
            for (int i = l; i < n-l-1; i++)
            {
                result[l][i] = num++;
            }
            
            // 从上到下
            for (int i = l; i < n-l-1; i++)
            {
                result[i][n-l-1] = num++;
            }
            
            // 从右到左
            for (int i = n-l-1; i > l; i--)
            {
                result[n-l-1][i] = num++;
            }
            
            // 从下到上
            for (int i = n-l-1; i > l; i--)
            {
                result[i][l] = num++;
            }
        }
        // 若为奇数
        if (n % 2 == 1)
        {
            result[loop][loop] = num;
        }
        return result;
    }

    public static void Main(string[] args)
    {
        Solution solution = new Solution();
        int[][] result = solution.GenerateMatrix(5);
        
        // 打印
        foreach (var res in result)
        {
            foreach (var r in res)
            {
                Console.Write($"{r}\t");
            }
            Console.WriteLine();
        }
    }
}